import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@views/Home'
import isLogin from '@utils'
import Cookie from 'js-cookie'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    component: Home,
    redirect: '/home/welcome',
    children: [
      {
        path: '/home/welcome',
        name: '欢迎登录',
        component: () => import('@views/Welcome'),
        meta: {
          needLogin: true,
          isNav: true,
          roles: ['admin', 'a', 'b']
        }
      },
      {
        path: '/artlist',
        name: '文章列表',
        component: () => import('@views/ArtList'),
        meta: {
          isNav: true,
          roles: ['admin', 'a', 'b']
        }
      },
      {
        path: '/artadd',
        name: '增加文章',
        component: () => import('@views/ArtAdd'),
        meta: {
          isNav: false
        }
      },
      {
        path: '/artedit/:id',
        name: '编辑文章',
        component: () => import('@views/ArtEdit'),
        meta: {
          isNav: false
        }
      },
      {
        path: '/message',
        name: '消息中心',
        component: () => import('@views/Message'),
        meta: {
          isNav: true,
          roles: ['admin', 'a', 'b']
        }
      },
      {
        path: '/setting',
        name: '设置',
        component: () => import('@views/Setting'),
        meta: {
          needLogin: true,
          isNav: true,
          roles: ['admin', 'a']
        }
      },
      {
        path: '/nofound',
        name: '404',
        component: () => import('@views/NoFound'),
        meta: {
          isNav: false
        }
      }
      // {
      //   path: '/home',

      //   meta: {
      //     isNav: false
      //   }
      // }
    ]
  },
  {
    path: '/login',
    name: '登录',
    component: () => import('@views/Login'),
    meta: {
      isNav: false
    }
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 获取缓存中的role
// 在这里获取只会执行一次 所以要放到路由导航里每次获取
// 导航守卫判断
router.beforeEach((to, from, next) => {
  // 当前访问路由是否需要登录
  if (to.meta.needLogin) {
    // 需要-->判断是否登录-->即缓存中是否有cookie
    if (isLogin()) {
      // 判断当前需要登录的路由是否有用户类型
      if (to.meta.roles) {
        console.log(to, 11)
        // 有-->判断当前路由用户角色是否包含缓存的中的用户
        if (to.meta.roles.includes(Cookie.get('role'))) {
          next()
        } else {
          // 没有即跳转至 没有权限页面
          next('/nofound')
        }
      } else {
        next()
      }
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
